package com.jt.permission.controller;

import com.jt.base.utils.Constant;
import com.jt.base.utils.PageUtil;
import com.jt.base.utils.R;
import com.jt.permission.helper.TransactionalHelper;
import com.jt.permission.model.Menu;
import com.jt.permission.model.User;
import com.jt.permission.service.UserService;
import com.jt.shiro.ShiroUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author longheping
 * @date 2018/6/21 15:44
 */
@RestController
@RequestMapping("admin/sys/user")
@Validated
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Resource
    private TransactionalHelper transactionalHelper;

    @RequestMapping("/search")
    @RequiresPermissions("sys:user:search")
    public R search(
            @Valid @Min(value = 0, message = "页码不能小于0") int page,
            @Valid @Max(value = 1000, message = "请求数量最大不能超过1000") int limit,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(name = "status", required = false) Integer status) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(username)) {
            criteria.andLike("username", "%" + username + "%");
        }
        if (userId != null) {
            criteria.andEqualTo("userId", userId);
        }
        if (status != null) {
            criteria.andEqualTo("status", status);
        }
        List<User> list = userService.selectListByExample(example, page, limit);
        return PageUtil.wrap(new PageInfo<>(list), R.ok());
    }

    @RequestMapping("/getMenu")
    public R getMenu() {
        R r = R.ok();
        User user = ShiroUtils.getUserEntity();
        if (user != null) {
            List<Menu> list = user.getMenus();
            r.put("data", list);
            r.put("username", user.getUsername());
        }
        return r;
    }

    @RequestMapping("/initPassword")
    public R initPassword(@Valid @Min(value = 0, message = "用户id必须大于0") Long userId) {
        User sysUser = userService.selectByKey(userId);
        if (sysUser != null) {
            userService.updatePassword(sysUser, Constant.SYS_USER_INIT_PASSWORD);
            return R.ok();
        } else {
            return R.error("用户不存在");
        }
    }

    /**
     * 修改密码
     */
    @RequestMapping("/updatePassword")
    public R updatePassword(@Valid @NotEmpty(message = "用户名不能为空") String username,
                                       @Valid @NotEmpty(message = "旧密码不能为空") String oldPassword,
                                       @Valid @Size(min = 6, message = "新密码不能为空且长度6位以上") String newPassword
    ) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        List<User> sysUsers = userService.selectListByExample(example);
        if (sysUsers == null || sysUsers.size() < 1) {
            return R.error("用户不存在");
        } else {
            User sysUser = sysUsers.get(0);
            logger.error("op=start_updatePassword, oldPassword={},dbPassword={}", sysUser.getPassword(), ShiroUtils.sha256(oldPassword, sysUser.getSalt()));
            if (sysUser.getPassword().equals(ShiroUtils.sha256(oldPassword, sysUser.getSalt()))) {
                userService.updatePassword(sysUser, newPassword);
                ShiroUtils.logout();
                return R.ok();
            } else {
                return R.error("旧密码不对");
            }
        }
    }

    /**
     * 保存用户
     */
    @RequestMapping("/save")
    public R save(@RequestBody JSONObject jb) {
        User user = JSONObject.toJavaObject(jb, User.class);
        String roleIds = jb.getString("roleIds");
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", user.getUsername());
        List<User> userList = userService.selectListByExample(example);
        if (userList != null && userList.size() > 0) {
            if (!userList.get(0).getUserId().equals(user.getUserId())) {
                return R.error("用户名已经存在");
            }
        }
        List<String> idStrList = Arrays.asList(roleIds.split(","));
        List<Long> roleIdList = new ArrayList<>();
        for (String s : idStrList) {
            if (StringUtils.isNumeric(s)) {
                roleIdList.add(Long.parseLong(s));
            }
        }
        transactionalHelper.saveOrUpdateUserRole(user, roleIdList);

        return R.ok();
    }

    /**
     * 审核用户
     *
     * @param userId
     * @param status
     * @return
     */
    @RequestMapping("/updateStatus")
    public R updateStatus(
            @Valid @Min(value = 0, message = "用户id必须大于0") long userId,
            @RequestParam("status") int status) {
        User sysUser = userService.selectByKey(userId);
        if (sysUser != null && sysUser.getUserId() != Constant.SUPER_ADMIN) {
            sysUser.setStatus(status);
            userService.update(sysUser);
            return R.ok();
        } else {
            return R.error("用户不存在");
        }
    }

    @RequestMapping("/get/{id}")
    public R get(@PathVariable String id) {
        return R.ok();
    }
}
